package third;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URLEncoder;

@WebServlet(name = "ImgServlet", value = "/imgservlet")
public class ImgServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        //response.setContentType("image/jpeg"); 浏览器直接打开
        //content-disposition
        response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode("图片.jpg", "utf-8")); //浏览器保存
        //返回图片
        //1 使用IO流读取图片  getServletContext() 获取servlet上下文
        String imgpath = request.getServletContext().getRealPath("/copy.jpg");
        //2 创建流
        FileInputStream fis = new FileInputStream(imgpath);
        byte[] buf = new byte[1024];
        int len = 0;
        ServletOutputStream os = response.getOutputStream();
        while ((len = fis.read(buf)) != -1) {
            os.write(buf, 0, len);
        }
        //3关闭
        fis.close();
        os.close();

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}
